package com.coderman.domainservice.member.infrast.gatawayimpl;

import com.alibaba.fastjson.JSON;
import com.coderman.domainservice.member.domain.gataway.IndicesStatisticsService;
import com.coderman.domainservice.member.domain.model.user.entity.IndicesStatisticsBO;
import com.coderman.domainservice.member.domain.model.user.valueobject.IndiceEnum;
import com.coderman.domainservice.member.infrast.cache.CacheKeyConstants;
import com.coderman.domainservice.member.infrast.cache.RedisTemplateService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * date: 2021/3/31
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class IndicesStatisticsServiceImpl implements IndicesStatisticsService {
    @Autowired
    private RedisTemplateService redisTemplateService;

    @Override
    public void updateIndicesStatistics(IndiceEnum indiceEnum, long userId, boolean incre) {
        String key = CacheKeyConstants.USER_INDICE_KEY + userId;
        String value = redisTemplateService.get(key);
        if(StringUtils.isEmpty(value)){
            //这里模拟下redis hash数据结构
            Map<String,Integer> indiceMap = new HashMap<>();
            indiceMap.put(indiceEnum.getCode(),1);
            redisTemplateService.set(key, JSON.toJSONString(indiceMap));
        }else {
            Map<String,Integer> indiceMap = JSON.parseObject(value,Map.class);
            indiceMap.put(indiceEnum.getCode(),indiceMap.get(indiceEnum.getCode())+1);
            redisTemplateService.set(key, JSON.toJSONString(indiceMap));
        }
    }

    @Override
    public List<IndicesStatisticsBO> getIndicesStatistics(long userId) {
        String key = CacheKeyConstants.USER_INDICE_KEY + userId;
        String value = redisTemplateService.get(key);
        Map<String,Integer> indiceMap = JSON.parseObject(value,Map.class);
        List<IndicesStatisticsBO> list = new ArrayList<>();
        indiceMap.forEach((k,v)->{
            IndicesStatisticsBO indicesStatisticsBO = new IndicesStatisticsBO();
            indicesStatisticsBO.setIndiceName(k);
            indicesStatisticsBO.setValue(v);
            list.add(indicesStatisticsBO);
        });
        return list;
    }
}
